package com.ysu.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.ysu.shop.utils.Result;
import com.ysu.shop.utils.UploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Slf4j
public class UtilController {

    @Value("${server.port}")
    private String port;

    @Value("${imgUrl}")
    private String imgUrl;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        if(!file.isEmpty()){
            String fileName = file.getOriginalFilename();  // 文件名
            String saveName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));  // 后缀名

            File newFile = new File(imgUrl+saveName);
            log.info("添加商品主图片的url--"+newFile.getAbsolutePath());
            // 上传图片到 -》 “绝对路径”
            file.transferTo(newFile);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("image","http://localhost:"+port+"/img/"+saveName);
            return Result.getSuccessResult(jsonObject);
        }else{
            return Result.getFailResult("","请上传商品的主图片");
        }
    }
}
